package cf.vbnm.ancitok.controller;

import cf.vbnm.ancitok.model.GeneralInfo;

import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
@RequestMapping("file")
public class FileServlet {
    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    private final Gson gson;
    private final SqlSession sqlSession;

    private static String getUploadPath(HttpServletRequest request){
        return request.getServletContext().getRealPath("./");
    }
    private static String getUploadPath(HttpServletRequest request, String middleDirName) {
        return getUploadPath(request) + File.separator + "upload" + File.separator + middleDirName + File.separator;
    }

    private static String getContextPath(String middleDirName) {
        return "upload" + File.separator + middleDirName + File.separator;
    }
    private static String getYearMonth() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return String.format("%d-%02d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
    }
    @Autowired
    public FileServlet(Gson gson, SqlSession sqlSession) {
        this.gson = gson;
        this.sqlSession = sqlSession;
    }



    @RequestMapping(value = "upload.action", method = POST)
    protected void doFileUpload(HttpServletRequest request, HttpServletResponse response, @Autowired GeneralInfo info) throws  IOException {
        PrintWriter writer = getPrintWriter(response);
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            info.setStatus(1);
            info.setInfo("Error: 不是 multipart/form-data");
            gson.toJson(info);
            writer.flush();
            return;
        }
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 如果目录不存在则创建
        String uploadDirName = getUploadPath(request, getYearMonth());
        File uploadDir = new File(uploadDirName);
        if (!uploadDir.exists()) {
            if (!uploadDir.mkdirs()) {
                info.setStatus(2);
                info.setInfo("Server Error");
                writer.print(gson.toJson(info));
                writer.flush();
                return;
            }
        }

        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {

                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        //文件名
                        String fileName = new File(item.getName()).getName();

                        File file;
                        file = new File(uploadDirName + File.separator + fileName);
                        String modifiedName;
                        int i = 1;
                        while (file.exists()) {
                            modifiedName = i++ + "-" + fileName;
                            file = new File(uploadDirName + File.separator + modifiedName);
                        }
                        File storeFile = file;

                        if (item.getFieldName().matches("file.*")) {
                            /*
                             * TODO
                             * */
                        }
                        // 在控制台输出文件的上传路径
                        System.out.println(file);
                        // 保存文件到硬盘
                        item.write(storeFile);
                    }
                }
            }

        } catch (Exception ex) {
            info.setStatus(1);
            ex.printStackTrace();
            info.setInfo(ex.getMessage());
            writer.print(gson.toJson(info));
            writer.flush();
            return;
        }
        info.setStatus(0);
        info.setInfo("success");
        writer.print(gson.toJson(info));
        writer.flush();
    }

    private PrintWriter getPrintWriter(HttpServletResponse response) throws IOException {
        response.setContentType("text/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        return response.getWriter();
    }
}
